<?php

namespace App\Console\Commands;

use App\Models\Base\LogEmail;
use App\Service\PlayerService;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class ServerMailPlan extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'server:mailPlan';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '定时发送邮件';

    /**
     * Create a new command instance.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $now_datetime = Carbon::now()->toDateTimeString();
        $mails = LogEmail::where('status', 0)
            ->where('send_at', '<=', $now_datetime)->get();
        if ($mails->isEmpty()) {
            return false;
        }
        foreach ($mails as $mail) {
            $mail_data = $mail->toArray();
            $mail_data['recipients'] = explode(',',$mail_data['recipients']);
            $result = PlayerService::sendGameMail($mail_data, $mail->emailItem);
            if (!$result) {
                Log::error('定时邮件发送失败:', [$mail->toArray()]);
                echo 'send mail error';
            }else{
                $mail->status=1;
                $mail->save();
            }
            echo 'send mail success';
        }
    }
}



